package net.interneteidee.utility;

import java.util.Iterator;

import javax.annotation.security.RolesAllowed;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.JTextComponent.KeyBinding;



@ManagedBean(name = "beanLogin")
@SessionScoped

public class BeanLogin {

	String username;
	String password;
	String ruolo;

	

	public BeanLogin() {
		// TODO Auto-generated constructor stub
	}

	public String login()  {

		CallbackHandler callbackHandler = new MyCallBackHandler(username, password); 
		LoginContext lg = null;
		

		try {
			lg = new LoginContext("controlloDB", callbackHandler);
			lg.login();
			setUserPrincipal();
			ruoloFromPrincipal();
			return "success";
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			System.err.println("Errore nella creazione del login Context");
			e.printStackTrace();
			return "error";
		}

		// Proviamo a effettuare l�autenticazione
	
			
		
			
		 
		        
		}
	
	
	
	public String logout(){
		
		HttpServletRequest request = getRequest();
		
		request.getSession().invalidate();
		return "logout";
		
	}

	/**
	 * Ottine il ruolo dal Principal
	 */
	public String ruoloFromPrincipal(){
		
		HttpServletRequest request = getRequest(); 
		
			if(request.isUserInRole("Admin"))
				ruolo = "Admin";
			else if(request.isUserInRole("Segreteria"))
				ruolo = "Segreteria";
			else if(request.isUserInRole("Cliente"))
				ruolo = "Cliente";
			
			return ruolo;

	}
	


	/**
	 * 
	 * @return restituisce la request Http
	 */
	private HttpServletRequest getRequest(){
		FacesContext context = FacesContext.getCurrentInstance();
        return (HttpServletRequest) context.getExternalContext().getRequest();
	}
	
	
	
	/**
	 * Con questo metodo forzo ad impostare il Principal all' interno della mia request
	 */
	private  void setUserPrincipal(){
		
		
        HttpServletRequest request = getRequest();
        
        try {
			request.login(username,password);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRuolo() {
		return ruolo;
	}

	public void setRuolo(String ruolo) {
		this.ruolo = ruolo;
	}
	


}
